package com.jdk.demo.nio.charbuffer;

import java.io.IOException;
import java.nio.CharBuffer;

public class SubSequenceDemo {
	
	// 创建表示此缓冲区的指定序列、相对于当前位置的新字符缓冲区。新缓冲区将共享此缓冲区的内容，即如果此缓冲区的内容是可变的，则修改一个缓冲区
	// 将导致另一个缓冲区被修改。新缓冲区的容量将为此缓冲区的容量，其位置将为position+start，其限制将为position+end
	public static void main(String[] args) throws IOException {
		CharBuffer buffer1 = CharBuffer.allocate(8);
		buffer1.append("ab123456");
		buffer1.position(2);
		buffer1.put("cde");
		buffer1.rewind();
		for (int i = 0; i < buffer1.limit(); i++) {
			System.out.print(buffer1.get());
		}
		System.out.println();
		
		buffer1.position(1);
		CharBuffer buffer2 = CharBuffer.allocate(4);
		System.out.println("A buffer2 position=" + buffer2.position());
		buffer1.read(buffer2);
		System.out.println("B buffer2 position=" + buffer2.position());
		buffer2.rewind();
		for (int i = 0; i < buffer2.limit(); i++) {
			System.out.print(buffer2.get());
		}
		System.out.println();
		
		buffer1.position(2);
		CharBuffer buffer3 = buffer1.subSequence(0, 2);
		System.out.println("C buffer3 capacity=" + buffer3.capacity() + ", position=" + buffer3.position() + " limit=" + buffer3.limit());
		// buffer3.rewind(); // buffer3的position为2，所以rewind之后，就会回归到0
		for (int i = buffer3.position(); i < buffer3.limit(); i++) {
			System.out.print(buffer3.get());
		}
		System.out.println();
	}

}
